<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/24
 * Time: 23:09
 */

namespace App\Services;
use App\Exceptions\NotExistException;
use App\Models\User as UserModel;

class User extends BaseService
{
    /**
     * 获取用户列表
     *
     * @param $limit
     * @param null $email
     * @return mixed
     */
    public function getList($limit, $email = null)
    {
        $users = UserModel::select();
        if($email !== null){
            $users->where('email', 'like', "%$email%");
        }
        return $users->paginate($limit);
    }

    /**
     * 获取单个用户信息
     *
     * @param $id
     * @return mixed
     * @throws NotExistException
     */
    public function show($id)
    {
        $user = UserModel::find($id);
        if(!$user) throw new NotExistException('用户不存在');
        return $user;
    }

    /**
     * 创建用户
     *
     * @param $data
     * @return UserModel
     */
    public function create($data)
    {
        $data['password'] = bcrypt($data['password']);
        return UserModel::create($data);
    }

    /**
     * 更新用户
     *
     * @param $id
     * @param $data
     * @return mixed
     * @throws NotExistException
     */
    public function update($id, $data)
    {
        $user = UserModel::find($id);
        $data = array_filter($data, function ($item){
            return $item != null;
        });
        if(!$user) throw new NotExistException('用户不存在');
        if(isset($data['password'])){
            $data['password'] = bcrypt($data['password']);
        }
        $user->update($data);

        return $user;
    }

    /**
     * 获取库存管理员
     *
     * @return mixed
     * @throws NotExistException
     */
    public function getCanteenManagers()
    {
        $managers = UserModel::where('type', 0)->get();
        if(count($managers) == 0) throw new NotExistException('你还没有添加库存管理员');
        return $managers;
    }
}